package cn.lzg.server.scanner;

import java.lang.reflect.Method;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import cn.lzg.common.core.annotation.SocketCmd;
import cn.lzg.common.core.annotation.SocketModule;

/**
 * handler扫描器
 * 
 * @author LizG
 *
 */
@Component
public class HandlerScanner implements BeanPostProcessor {

	/**
	 * 实例化之前处理
	 */
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	/**
	 * 实例化之后处理
	 */
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		Class<? extends Object> clazz = bean.getClass();
		Class<?>[] interfaces = clazz.getInterfaces();
		if (interfaces != null && interfaces.length > 0) {
			for (Class<?> interFace : interfaces) {
				SocketModule socketmodule = interFace.getAnnotation(SocketModule.class);
				if (socketmodule == null) {
					continue;
				}
				Method[] methods = interFace.getMethods();
				if (methods != null && methods.length > 0) {
					for (Method method : methods) {
						if (method == null) {
							continue;
						}
						SocketCmd socketcmd = method.getAnnotation(SocketCmd.class);
						//加入执行管理器中
						Invoker invoker = Invoker.valueOf(bean, method);
						InvokerHoler.addInvoker(socketmodule.module(), socketcmd.cmd(), invoker);
					}
				}
			}
		}
		return bean;
	}

}
